<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>Client</title>
</head>
<body>
<form onsubmit="return false">
    <textarea id="message" style="height: 300px; width: 300px"></textarea>
    <input type="button" value="发送消息" onclick="send()"/>
    <textarea id="responseText" style="height: 300px; width: 300px"></textarea>
    <input type="button" value="清空内容" onclick="clear1()"/>
</form>
<script style="javascript">
    var socket;
    if (window.WebSocket) {
        socket = new WebSocket("ws://localhost:8888/chat");

        // 收到消息时
        socket.onmessage = function (event) {
            var responseText = document.getElementById("responseText");
            responseText.value = responseText.value + event.data + "\n";
        }

        // 连接打开时
        socket.onopen = function () {
            var responseText = document.getElementById("responseText");
            responseText.value = "已连接\n";
        }

        // 连接关闭时
        socket.onclose = function () {
            var responseText = document.getElementById("responseText");
            responseText.value = "已关闭\n";
        }

    } else {
        alert("你的浏览器不支持WebSocket");
    }

    function send() {
        var message = document.getElementById("message").value;
        console.log(message);
        if (socket && socket.readyState == WebSocket.OPEN) {
            socket.send(message);
        } else {
            alert("请先连接");
        }
    }
    function clear1() {
        var responseText = document.getElementById("responseText");
        responseText.value = "";
    }
</script>
</body>
</html>